package com.mymvc.controller.upload;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author 王俊彪
 * @version 1.0
 */
@Controller
public class UploadController {

    @RequestMapping("/upload")
    public String upload(){
        return "upload";
    }
    @RequestMapping("/uploadFile")
    public String uploadFile(MultipartFile uploadFile, HttpServletRequest request) {
        //判断是否为非空
        if(uploadFile!=null && !StringUtils.isEmpty(uploadFile.getOriginalFilename())){
            //获取上传文件名称
            String originalFilename = uploadFile.getOriginalFilename();
            //解决文件名重名的问题
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String exentsion = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFileName = uuid+exentsion;

            //开始上传
            try {
                uploadFile.transferTo(new File(request.getServletContext().getRealPath("/"),newFileName));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        return "success";
    }
}
